function ascFileWrite(Z,xmi,xma,ymi,yma,filenout,nodataval)
%ascFileWrite - Writing an ascii .asc ArcGIS-style file 
%
%       ascFileWrite(A,xmi,xma,ymi,xma,FILENOUT,NODATAVAL)
%
% This function writes an ASCII file FILENOUT (.asc file) related to the 
% field represented by the matrix A (e.g. elevation of a Digital Elevation
% Model, velocity field, strain field, ...) on the basis of the grid limits 
% (xmi,ymi) and (xma,yma). 
% If FILENOUT is undefined or empty, this filename can be interactively
% managed.
% The numeric input NODATAVAL is the value assigned to the cells where no
% numeric data are available, i.e. the matrix elements are NaN. 
% If NODATAVAL is unassigned or empty, the default choice NODATAVAL = -9999 
% is used.  
% The generated file has the 6-rows header: 
%
%    ncols           xxx
%    nrows           xxx
%    xllcorner       xxx
%    yllcorner       xxx
%    cellsize        xxx
%    NODATA_value    xxx
%
% where
%   
%   ncols (nrows) is the number of grid lines along X-axis (Y-axis).
%   Clearly, ncols and nrows must be integer numbers;
% 
%   xllcorner (yllcorner) is the X-coordinate (Y-coordinate) of the grid 
%   origin by lower-left corner of the cell;
%
%   cellsize is the cell size (equal for X- and Y- direction).
%
%   NODATA_value is the value related to no data cells (NaN in the input
%   matrix) 

% G. Teza, 2015, 2022

if nargin < 7 || isempty(nodataval)
    nodataval = -9999; 
end
if nargin < 6 || isempty(filenout)
    [filen,pathn] = uiputfile(...
        {'*.asc','ESRI ArcGIS ASCII files (*.asc)'},...
        'ASCII OUTPUT DTM FILE');
    if isequal(filen,0) || isequal(pathn,0)
        filenout = [];
    else
        [~,filenrid,ext] = fileparts(filenout);
        if ~strcmp(ext,'.asc')
            filen = [filenrid '.asc'];
            filenout = fullfile(pathn,filen);
        end
    end 
end
if isempty(filenout)
    fprintf('\n NO ASCII FILE GENERATION\n'); 
    return; 
end

[nr,nc] = size(Z);

% header:
tmp = []; 
save(filenout,'tmp','-ascii','-double');    % output file inizialization
fid = fopen(filenout,'w');
formatSpec = '%s %s\r\n';                   % format header rows
C = {'ncols',num2str(nc);
     'nrows',num2str(nr);
     'xllcorner',num2str(xmi);
     'yllcorner',num2str(ymi);
     'cellsize',num2str(mean([(xma-xmi)/nc,(yma-ymi)/nr]));
     'NODATA_value',num2str(nodataval)};
for k = 1:6
    fprintf(fid,formatSpec,C{k,:});
end
fclose(fid);

% data:
Z = flipud(Z); 
I = isnan(Z);
Z(I) = nodataval;

save(filenout,'Z','-ascii','-double','-append');